package com.majun.base.operate;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * just：创建一个包含单个元素的Mono或多个元素的Flux；
 * 
 * empty：创建一个空的Flux或Mono；
 * 
 * defer：在订阅时动态创建一个新的Flux或Mono；
 * 
 * fromArray：从数组创建Flux；
 * 
 * fromIterable：从Iterable对象创建Flux；
 * 
 * range：创建一个从start到end的整数序列Flux；
 * 
 * interval：创建一个按时间间隔发布数据的Flux；
 */
public class CreationExample {
	public static void main(String[] args) {
		// 示例 1: 使用 Mono 创建操作符
		// just：创建一个包含单个元素的Mono或多个元素的Flux；
		Mono<String> monoJust = Mono.just("Hello, Mono");
		Mono<String> monoEmpty = Mono.empty();
		// defer：在订阅时动态创建一个新的Flux或Mono；
		Mono<String> monoDefer = Mono.defer(() -> Mono.just("Deferred Mono"));

		// 订阅 Mono 并打印结果
		monoJust.subscribe(System.out::println);
		monoEmpty.subscribe(System.out::println, Throwable::printStackTrace, () -> System.out.println("Completed"));
		monoDefer.subscribe(System.out::println);

		// 示例 2: 使用 Flux 创建操作符
		Flux<String> fluxJust = Flux.just("Ajust", "Bjust", "Cjust");
		Flux<String> fluxFromArray = Flux.fromArray(new String[] { "AfromArray", "BfromArray", "CfromArray" });
		List<String> list = Arrays.asList("AfromIterable", "BfromIterable", "CfromIterable");
		Flux<String> fluxFromIterable = Flux.fromIterable(list);
		Flux<String> fluxFromStream = Flux.fromStream(Stream.of("AfromStream", "BfromStream", "CfromStream"));
		Flux<Integer> fluxRange = Flux.range(1, 5);
		Flux<Long> fluxInterval = Flux.interval(Duration.ofSeconds(1));
		Flux<String> fluxDefer = Flux.defer(() -> Flux.just("Deferred Flux"));

		// 订阅 Flux 并打印结果
		fluxJust.subscribe(System.out::println);
		fluxFromArray.subscribe(System.out::println);
		fluxFromIterable.subscribe(System.out::println);
		fluxFromStream.subscribe(System.out::println);
		fluxRange.subscribe(System.out::println);
		fluxInterval.take(5).subscribe(System.out::println);
		fluxDefer.subscribe(System.out::println);
	}
}
